package com.example.englishwars2d;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class MenuActivity extends Activity {
	MyDatabaseOpenHelper mDBHelper;
	Cursor mCursor = null;
	ListView list;
	public final String TAG="MenuActivity";
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.menu_list_activity);
		mDBHelper = new MyDatabaseOpenHelper(this);
		list = (ListView)findViewById(R.id.listView1);
		try {
			boolean bResult = isCheckDB(this); // DB가 있는지?
			Log.d(TAG, "DB Check=" + bResult);
			if (!bResult) { // DB가 없으면 복사
				copyDB(this);
			} else {
				if (mCursor != null) {
					mCursor.close();
					mCursor = null;
				}
				SQLiteDatabase db = mDBHelper.getReadableDatabase();
				String sql = "SELECT "
						+DBConstant.SongListTable.ID+", "
						+DBConstant.SongListTable.SONG_NUM+", "
						+DBConstant.SongListTable.TITLE+", "
						+DBConstant.SongListTable.ARTIST
						+" FROM " + DBConstant.SongListTable.TABLE_NAME;
				mCursor = db.rawQuery(sql, null);
				String[] from = { DBConstant.SongListTable.SONG_NUM,
						DBConstant.SongListTable.TITLE, 
						DBConstant.SongListTable.ARTIST };
				int[] to = {R.id.songId, R.id.songTitle, R.id.Artist };
				SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.item_layout, mCursor, from, to, 0);
				list.setAdapter(adapter);
				list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
				list.setOnItemClickListener(new OnItemClickListener() {

					public void onItemClick(AdapterView parent, View view, int position, long id)  {
						String mes;
						mCursor.moveToPosition(position);
						mes = "Select Item = " + mCursor.getString(2);
						Log.i(TAG, "Selected:"+mes);
						Intent i = new Intent(MenuActivity.this, CollisionTest.class);
						i.putExtra("song_num", mCursor.getInt(1));
						startActivity(i);
					}
				});
			}
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
		}
	}

	// DB가 있나 체크하기
	public boolean isCheckDB(Context mContext) {
		String filePath = Environment.getDataDirectory().getAbsolutePath()
				+ "/data/" + MyDatabaseOpenHelper.PACKAGE_NAME + "/databases/"
				+ MyDatabaseOpenHelper.DB_NAME;
		Log.d(TAG, "isCheckDB: "+ filePath);
		File file = new File(filePath);
		
		if (file.exists()) {
//			file.delete();
//			finish();
			return true;
		}

		return false;
	}

	// DB를 복사하기
	// assets의 /db/xxxx.db 파일을 설치된 프로그램의 내부 DB공간으로 복사하기
	public void copyDB(Context mContext) {
		Log.d(TAG, "copyDB");
		AssetManager manager = ((MenuActivity)mContext).getAssets();
		String folderPath = Environment.getDataDirectory().getAbsolutePath()
				+ "/data/" + MyDatabaseOpenHelper.PACKAGE_NAME + "/databases";
		String filePath = folderPath + "/"+MyDatabaseOpenHelper.DB_NAME;
		Log.d(TAG, "copyDB: "+ folderPath);
		Log.d(TAG, "copyDB: "+ filePath);
		File folder = new File(folderPath);
		File file = new File(filePath);

		FileOutputStream fos = null;
		BufferedOutputStream bos = null;
		try {
			InputStream is = manager.open("db/"+ MyDatabaseOpenHelper.DB_NAME);

			BufferedInputStream bis = new BufferedInputStream(is);

			if (folder.exists()) {
				Log.d(TAG, "Folder Exist");
			} else {
				Log.d(TAG, "Folder Not Exist");
				folder.mkdirs();
			}

			if (file.exists()) {
				Log.d(TAG, "File Exist");
				file.delete();
				file.createNewFile();
			}

			fos = new FileOutputStream(file);
			bos = new BufferedOutputStream(fos);
			int read = -1;
			byte[] buffer = new byte[1024];
			while ((read = bis.read(buffer, 0, 1024)) != -1) {
				bos.write(buffer, 0, read);
			}

			bos.flush();

			bos.close();
			fos.close();
			bis.close();
			is.close();

		} catch (IOException e) {
			Log.e("ErrorMessage : ", e.getMessage());
		}
	}

}
